# -*- coding: utf-8 -*-

import sys

sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json,time
from common.helper import Helper
from urllib.parse import urlencode
from pprint import pprint

class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "国华少儿成长无忧重大疾病保险"
    def genProductInfo(self):
        plan = {
            #年龄段
            "year":[str(i) for i in range(0,8)],
            #性别
            "gender":["F","M"],
            #职业
            "occupation":["学生","学龄前儿童"],
            #保障期限
            "expire":["25岁"],
            #交费方式
            "payType":["年交"],
            #交费期间
            "interval":["10"],
            #保障金额
            "money":["300000","500000","800000","1000000","1500000","2000000"]

        }
        for v in product(plan["year"],plan["gender"],plan["occupation"],plan["expire"],plan["payType"],plan["interval"],plan["money"]):
            self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(
                v[0],v[1],v[2],v[3],v[4],v[5],v[6]
            ))
            self.mysql._conn.commit()
            print(domain[self.name]["insert_sql"].format(
                v[0],v[1],v[2],v[3],v[4],v[5],v[6]
            ))
    #执行爬虫
    def requestJson(self,dt=None):

        data = {
            "inside":"",
            "ebizAppntDto.sex": "0" if dt["gender"] == "F" else "1",
            "ebizAppntDto.birthday":"",
            "age": "0",
            "appAge":"",
            "birthdayLock":"",
            "ebizAppntDto.sexLock":"",
            "calLock":"",
            "channel": "gx",
            "ebizOrderDto.orderType": "2",
            "ebizOrderDto.manageOrg":"",
            "ebizOrderDto.isLockedOrg": "0",
            "ebizOrderDto.orderNo":"",
            "ebizOrderDto.orderAmount":"",
            "ebizOrderDto.productCode": "964",
            "ebizProduct.mainRiskCode":"",
            "ebizOrderInsuranceDto.payEndYear": "10",
            "itemCode": "GX1166V1",
            "ebizOrderDto.productChannel": "01",
            "ebizOrderInsuranceDto.payEndYearFlag": "Y",
            "ebizOrderInsuranceDto.insuYearFlag": "A",
            "ebizOrderInsuranceDto.isMainRisk": "1",
            "ebizOrderInsuranceDto.mainRiskCode": "1166V1",
            "ebizOrderInsuranceDto.riskCode": "1166V1",
            "ebizOrderInsuranceDto.riskName": "国华少儿成长无忧重大疾病保险",
            "ebizOrderInsuranceDto.years": "25",
            "orderRecommendDTO.code":"",
            "orderRecommendDTO.remark":"",
            "orderRecommendDTO.remark2":"",
            "orderRecommendDTO.remark3":"",
            "orderRecommendDTO.remark4":"",
            "thirdOrderNo":"",
            "thirdType":"",
            "thirdProductCode":"",
            "thirdUserId":"",
            "ebizInsuredDto.birthday": "{year} - 01 - 01".format(year = str(2020-int(dt["year"]))),
            "ebizInsuredDto.sex": "0" if dt["gender"] == "M" else "1",
            "ebizInsuredDto.occupationType": "1",
            "ebizInsuredDto.occupationCode": "2147001",
            "ebizInsuredDto.occupationName": dt["occupation"],
            "ebizOrderInsuranceDto.insuYear": "25",
            "ebizOrderInsuranceDto.payIntv": "12",
            "ebizOrderInsuranceDto.payYears": "10",
            "ebizOrderInsuranceDto.amt": dt["money"],
            "ebizOrderInsuranceDto.prem":"",
            "_addOrderInsuranceListDto[0].riskCode": "on",
            "_addOrderInsuranceListDto[1].riskCode": "on",
            "algorithmType": "1"
        }

        payload = urlencode(data).replace("+","")
        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)
        if r.status_code == 200:
            data = {
                "name":self.name,
                "id":dt["id"],
                "price":r.text
            }
            self.mysql.updatePrice( data )
        else:
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            self.mysql.updateTask( data )
            print("\n/*更新产品价格信息失败:%d*/"%dt["id"])

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:

                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }

            self.mysql.updateTask(data)

            self.requestJson(dt)
